package com.wanxi.servlet;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.dto.ResultDTO;
import com.wanxi.service.Impl.ManagerServiceImpl;
import com.wanxi.service.ManagerService;
import com.wanxi.vo.ManagerVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        清除session
        req.getSession().removeAttribute("managerName");
//        页面转发
        req.getRequestDispatcher("/admin/login.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        乱码处理、传输格式处理
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
//        数据封装
        String managerName=req.getParameter("managerName");
        String password=req.getParameter("password");
        String code=req.getParameter("code");
        String vCode=(String) req.getSession().getAttribute("vCode");
        ManagerVO managerVO=ManagerVO.builder().managerName(managerName).password(password).code(code).vCode(vCode).build();
//        提交给service处理
        ManagerService managerService =new ManagerServiceImpl();
        ResultDTO resultDTO= managerService.login(managerVO);
//        过滤器
        if (resultDTO.getMsg().equals("success")) {
            req.getSession().setAttribute("managerName", managerName);
        }

//        发送结果给前端
        resp.getWriter().println(JSONObject.toJSONString(resultDTO));
    }
}
